package com.zhouyong.netty;

import com.zhouyong.netty.config.ServerChannelInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * netty服务端
 *
 * @author 99Savage
 * @date 2023/3/17 9:38
 */
@Component
@Slf4j
public class NettyServer {

    @Value("${netty.server.host}")
    private String host;

    @Value("${netty.server.port}")
    private Integer port;

    @Resource
    private ServerChannelInitializer serverChannelInitializer;

    @PostConstruct
    public void init() {
        log.info("netty正在初始化中...");
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            ChannelFuture future = new ServerBootstrap()
                    .group(boss, worker)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(serverChannelInitializer)
                    .bind(host, port);
            log.info("netty初始化结束...");
            // 同步关闭服务端
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("异常,cause:【】", e);
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}
